﻿#ifndef Lock_h__2013_7_26__22_44
#define Lock_h__2013_7_26__22_44


#define DF_LOCKED(obj) df::Locked DF_MIX_LINENAME(LOCK,__LINE__)(obj)


namespace df
{
	class Lock 
	{
	public:

#ifdef WIN32
		inline Lock()
		{
			///初始化
			InitializeCriticalSection(&Loc);
		}
		inline ~Lock(void)
		{
			DeleteCriticalSection(&Loc);
		}
		///上锁
		inline void Start()
		{
			EnterCriticalSection(&Loc);
		}
		///解锁
		inline void End()
		{
			LeaveCriticalSection(&Loc);
		}
	private:
		CRITICAL_SECTION Loc;
#else
		inline Lock()
		{
			///初始化
			pthread_mutex_init(&Loc,NULL);
		}
		inline ~Lock(void)
		{
			pthread_mutex_destroy(&Loc);
		}
		///上锁
		inline void Start()
		{
			pthread_mutex_lock(&Loc);
		}
		///解锁
		inline void End()
		{
			pthread_mutex_unlock(&Loc);
		}
	private:
		pthread_mutex_t Loc;
#endif

		DF_DISABLE_COPY_ASSIGN(Lock);
	};

	class Locked
	{
	public:
		Locked(Lock & l):Loc(l)
		{
			l.Start();
		}
		~Locked()
		{
			Loc.End();
		}
	private:
		Lock & Loc;

		DF_DISABLE_COPY_ASSIGN(Locked);
	};

}

#endif // Lock_h__2013_7_26__22_44